/*
 * @Description:树操作
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-26 17:04:45
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-09 15:51:55
 */
const defaultTreeConfig = {
  id: 'id',
  pId: 'pId',
  children: 'children'
}

const BfsTreeData = (treeData, cb, treeConfig) => {
  const config = Object.assign({}, defaultTreeConfig, treeConfig)
  // const tagetData = cloneDeep(treeData)
  if (!treeData || !treeData.length) {
    return []
  }
  let stack = []
  for (let i = 0; i < treeData.length; i++) {
    stack.push(treeData[i])
  }
  let item = null
  while (stack.length) {
    item = stack.shift()
    if (cb) {
      const result = cb(item)
      if (result) {
        return result
      }
    }
    if (item[config.children] && item[config.children].length > 0) {
      stack = stack.concat(item[config.children])
    }
  }
  return treeData
}

const childrenTreeData = (treeData, id, result = []) => {
  if (!treeData || !treeData.length) {
    return []
  }
  for (let i = 0; i < treeData.length; i++) {
    const target = treeData[i]
    if (`${target.depId}` === id) {
      if (target.children && target.children.length > 0) {
        childrenTreeData(target.children, id, result)
      } else {
        result.push()
      }
    } else {
      childrenTreeData(treeData, id, result)
    }
  }
  return result
}

const treeToList = (tree, treeConfig) => {
  const config = Object.assign({}, defaultTreeConfig, treeConfig)
  const { children } = config; const result = [...tree]
  for (let i = 0; i < result.length; i++) {
    if (!result[i][children]) { continue }
    result.splice(i + 1, 0, ...result[i][children])
  }
  return result
}

const listToTree = (list, treeConfig, callBack) => {
  const config = Object.assign({}, defaultTreeConfig, treeConfig)
  const info = list.reduce((map, node) => {
    if (!map[node[config.id]]) {
      map[node[config.id]] = node
      node[config.children] = []
    }
    return map
  }, {})
  return list.filter(v => {
    callBack && callBack(v)
    if (info[v[config.pId]]) {
      info[v[config.pId]][config.children].push(v)
    }
    return !v[[config.pId]]
  })
}
module.exports = {
  listToTree,
  BfsTreeData,
  childrenTreeData,
  treeToList
}
